<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\DB;
// use Model\
use Closure;

class CheckLoginRbac
{
    /**
     * [handle 检查登录状态 / 权限]
     * @Author   孙丽男
     * @DateTime 2018-06-05
     * @version  6.2
     */
    public function handle($request, Closure $next)
    {
        $uid = session('uid');

        if (!$uid) {
            
            return response()->json([  
                'code' => 1001,  
                'msg' => '未登录', 
            ]); 
        }
        $num = session('number');
        if ($num == 'admin') {
            return $next($request);
        }
        //获取当前路由
        $url = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; 
        $funllurl = 'http://'.$url;
        $rolesObj = Db::table('user_role')
                        ->where('user_id',$uid)
                        ->join('roles','user_role.role_id','=','roles.id')
                        ->join('role_power','role_power.role_id','=','roles.id')
                        ->join('power','role_power.power_id','=','power.id')
                        ->select('url')
                        ->get();

        $rolesArr = json_decode(json_encode($rolesObj),true);          
        //去重
        foreach ($rolesArr as $k => $v){

            $v=implode(',',$v);

            $rolesArrNew[$k]=$v;
        }
        $rolesArrNew=array_unique($rolesArrNew);

        if (in_array($url,$rolesArrNew) || in_array($funllurl, $rolesArrNew) ) {

            return $next($request);

        }else{

            return response()->json([  
                'code' => 1006,  
                'msg' => '没有权限', 
            ]); 

        }


    }

}